//
//  YSZNetworkTools.swift
//  swiftweibo6
//
//  Created by ysz on 15/11/24.
//  Copyright © 2015年 user. All rights reserved.
//

import UIKit

import AFNetworking

//网络请求枚举
enum YSZNetworkMethod: String
{
    case GET = "GET"
    case POST = "POST"
}


//错误统一管理
enum YSZNetworkToolError: Int
{
    case EmptyAccessToken = -1
    case EmptyUid = -2
    var dseciption: String
        {
            switch self
            {
            case .EmptyAccessToken:
                return "access_token 没有值"
            case .EmptyUid:
                return "uid 没有值"
            }
    }
    
    func error() -> NSError
    {
        return NSError(domain: "", code: self.rawValue, userInfo:["dseciption": self.dseciption ])
    }
}

class YSZNetworkTools: AFHTTPSessionManager
{
    static let shardInsatance: YSZNetworkTools =
    {
        let baseURL = NSURL(string: "https://api.weibo.com/")
        let tools = YSZNetworkTools(baseURL: baseURL)
        tools.responseSerializer.acceptableContentTypes?.insert("text/plain")
        return tools
    }()
    //申请应用分配的id
    private let client_id = "1969807811"
    //申请应用的appsecretID
    private let client_secret = "678257a3e2e4c454e9ec138d1432e683"
    //授权回调的地址
    let redirect_uri = "http://www.baidu.com/"
    // 返回授权界面的URL地址
    func oauthURL() -> NSURL
    {
        let urlstr="https://api.weibo.com/oauth2/authorize?client_id=\(client_id)&redirect_uri=\(redirect_uri)"
        return NSURL(string: urlstr)!
    }
    
    //加载用户信息
    func loadUserInfo(finished: (result: [String: AnyObject]?, error:NSError?)-> ())
    {
        guard let access_token = YSZUserAccount.loadUserAccount()?.access_token else{
            print("token 没有值")
            return
        }
//        YSZUserAccount.loadUserAccount()?.uid = nil
        guard let uid = YSZUserAccount.loadUserAccount()?.uid else
        {
            print("uid没值")
            return
        }
        
        let urlString = "2/users/show.json"
        
        let parameters = [
            "uid": uid
        ]
        request(requestMethod: YSZNetworkMethod.GET, urlString: urlString, parameter: parameters, needAccessToken: true, finished: finished)
        
    }
    ///加载微博数据
    func loadStatus(finished: (result: [String: AnyObject]? , error: NSError?)-> ())
    {
//        guard let access_token = YSZUserAccount.loadUserAccount()?.access_token
//        else
//        {
//            print("token 没有值")
//            return
//        }
        let urlString = "https://api.weibo.com/2/statuses/home_timeline.json"
        let parameters = [String: AnyObject]()
        request(requestMethod: YSZNetworkMethod.GET, urlString: urlString, parameter: parameters, needAccessToken: true, finished: finished)
    }
    //网络工具类加载AccessToken, 只负责加载数据,让别人来处理数据(通过闭包)
    func loadAccessToken(code: String, finished: (result: [String:AnyObject]?,error: NSError?) -> ())
    {
        print("code: \(code)")
        let urlstring="https://api.weibo.com/oauth2/access_token"
        let parameters = [
            "client_id": client_id,
            "client_secret": client_secret,
            "grant_type": "authorization_code",
            "code": code,
            "redirect_uri": redirect_uri
        ]
        
        request(requestMethod: YSZNetworkMethod.POST, urlString: urlstring, parameter: parameters, needAccessToken: false, finished: finished)
    }
    //定义类型别名
    typealias NetworkCellback = (result: [String: AnyObject]? , error: NSError?)-> ()
    /**
    抽取get,post方法，网络请求的统一入口都是这个当法
    
    - parameter requestMethod:   请求方式get,post
    - parameter urlString:       url地址
    - parameter parameter:       参数
    - parameter finished:        回调闭包
    */
    func request(requestMethod requestMethod: YSZNetworkMethod, urlString: String, var parameter: [String: AnyObject], needAccessToken: Bool, finished:NetworkCellback)
    {
        if needAccessToken
        {
            //判断access_token 是否有值，有就拼接没有就返回
            guard let access_token = YSZUserAccount.loadUserAccount()?.access_token
            else
            {
                let error = YSZNetworkToolError.EmptyAccessToken.error()
                finished(result: nil, error: error)
                return
            }
        //拼接
            parameter["access_token"] = access_token
        }
        //准备成功的闭包
        let successCallback =
        {
            (task: NSURLSessionDataTask, result: AnyObject) -> Void in
            finished(result: result as? [String: AnyObject], error: nil)
        }
        //失败的闭包
        let failureCallback =
        {
            (task: NSURLSessionDataTask?,error:NSError)-> Void in
            finished(result: nil, error: error)
        }
        //根据请求方式，发送对应请求
        switch requestMethod
        {
        case .GET:
                GET(urlString, parameters: parameter, success: successCallback, failure: failureCallback)
        case .POST:
                POST(urlString, parameters: parameter, success: successCallback, failure: failureCallback)
        }
        
    }
    
    
    
    
    
}
